
const COS = require('cos-nodejs-sdk-v5');
import { BadRequestException, Injectable } from '@nestjs/common';
const fs = require('fs');
@Injectable()
export class OssService {
    private client: any;
    public constructor() {
        this.client = new COS({
            // 必选参数
            SecretId: process.env.TX_OSS_SECRETID,
            SecretKey: process.env.TX_OSS_SECRETKEY,
            // 可选参数
            FileParallelLimit: 3,    // 控制文件上传并发数
            ChunkParallelLimit: 8,   // 控制单个文件下分片上传并发数，在同园区上传可以设置较大的并发数
            ChunkSize: 1024 * 1024 * 8,  // 控制分片大小，单位 B，在同园区上传可以设置较大的分片大小
            Proxy: '',
            FollowRedirect: false,
        })
    }
    //上传图片
    public async putObject(fileName, file) {
        return new Promise((resolve, reject) => {
            this.client.putObject({
                Bucket: process.env.TX_OSS_BUCKET,
                Region: process.env.TX_OSS_REGION,
                Key: fileName,
                Body: file.buffer,
                ContentLength: file.size,
            }, function (err, data) {
                resolve(data)
            });
        })
    }
    // 上传文件到oss 并返回  图片oss 地址
    public async putOssFile(file): Promise<void | unknown> {
        const temp = file.originalname.split('.');
        const fileType = temp[temp.length - 1];
        const lastName = '.' + fileType;
        const fileName = new Date().getTime() + lastName;
        const data = await this.putObject(fileName, file)
        if (data) {
            return data
        } else {
            throw new BadRequestException('上传失败');
        }

    }
    public async isHaveFile(fileName) {
        return new Promise((resolve, reject) => {
            // 获取存储桶下所有文件
            this.client.getBucket({
                Bucket: process.env.TX_OSS_BUCKET,
                Region: process.env.TX_OSS_REGION,
            }, function (err, data) {
                console.log(err|data)
            });
        })
    }
}